<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Crypt;
use Hash;
use DB;

class UserController extends Controller
{
    //add
	public function add()
	{
		return view('admin.user.add', ['title' => '用户添加']);
	}
	
	//insert
	public function insert(Request $request)
	{

		// return 111;
		//表单验证
        $this->validate($request, [
            //验证name 不能为空 最小6位 最大18位
            'user_name' => 'required|min:5|max:18',
            //验证email 不能为空 并且 必须是email地址
            'email' => 'required|email',
            'password' => 'required|min:5|max:18',
            //same 相同  和: 后的变量相同
            'repassword' => 'required|same:password'
        ],[
            //  错误提示写位中文
            'user_name.required' => '用户名不能为空',
            'user_name.min' => '用户名最少输入5位',
            'user_name.max' => '用户名最大输入18位',
            'email.required' => '邮箱不能为空',
            'email.email' => '邮箱格式不正确',
            'password.required' => '密码不能为空',
            'password.min' => '密码最小长度不能小于5位数',
            'password.max' => '密码最大长度不能大于18位数',
            'repassword.required' => '确认密码不能为空',
            'repassword.same' => '两次密码不一致'
        ]);


        $data = $request -> except('_token', 'repassword');
		
		//处理密码字段
		// $data['password'] = Crypt::encrypt($data['password']);
		// echo $data['password'];
		// die();
		// $p = Crypt::decrypt('eyJpdiI6ImNURmhGaEhFSXhRbnNWUmdwUjFxRmc9PSIsInZhbHVlIjoiY29DWjZ5UUpwZGpvclhtTGR4XC90VVE9PSIsIm1hYyI6IjcyZmFhOGQ4NmUwOTJkOWI3ZjYzMTdhZDUxODUwNzg3ZGQ3YWY0NDAzZDQzYzk1YzlkNWU3ODY4N2RkMTYxNDUifQ==');
		
		// $data['password'] = Hash::make($data['password']);
		// dd($data['password']);
		// $res = Hash::check('123', '$2y$10$82eF2BkbnoLeqnrfD1K59e1pv5WQJwkCfUEb6fy9xwUmtN0ruotye');
		// dd($res);
		
		$data['password'] = Crypt::encrypt($data['password']);
		
		//处理status字段
		$data['status'] = 0;
		//处理token字段
		$data['remember_token'] = str_random(50);
		
		//处理时间
		$time = time(); 
		$data['created_at'] = $time;
		$data['updated_at'] = $time;
		
		//处理头像
		if($request -> hasfile('photo'))
		{
			if($request -> file('photo') -> isValid())
			{
				$suffix = $request -> file('photo') -> getClientOriginalExtension();
				$fileName = time() . mt_rand(10000,99999) . '.' . $suffix;
				//移动文件
				if(!file_exists('./uploads/yhtx'))
				{
					mkdir('./uploads/yhtx', true, '777');
				}
				$move = $request -> file('photo') -> move('./uploads/yhtx', $fileName);
				
				if($move)
				{
					$data['photo'] = $fileName;
				}else
				{
					$data['photo'] = 'default.jpg';
				}
			}else
			{
				$data['photo'] = 'default.jpg';
			}
		}else
		{
			$data['photo'] = 'default.jpg';
		}
		
		// dd($data);
		$res = DB::table('users') -> insert($data);
		if($res)
		{
			return redirect('/admin/user/index') -> with(['info' => '添加成功']);
		}else
		{
			return back() -> with(['info' => '添加失败']);
		}
	}
	
	//index
	public function index(Request $request)
	{
		//查询数据
		// $data = DB::table('users') -> where('user_name', 'like', '%' . $request -> input('keywords') . '%') -> paginate($request -> input('num', 10));

		//高级where条件
		$data = DB::table('users') -> where(function($query) use($request)
		{
			$query -> where('user_name', 'like', '%' . $request -> input('keywords') . '%');
		}) -> paginate($request -> input('num', 10));
		return view('admin.user.index', ['data' => $data, 'request' => $request -> all()]);
	}

	//ajax修改用户状态
	public function ajaxStatus(request $request)
	{
		$id = $request -> input('id');
		//查询
		$status = DB::table('users') -> where('id', $id) -> first() -> status;
		
		//判断
		if($status == 0)
		{
			$res = DB::table('users') -> where('id', $id) -> update(['status' => 1]);
			
			if($res)
			{
				return 1;
			}else
			{
				return 2;
			}
		}elseif($status == 1)
		{
			$res = DB::table('users') -> where('id', $id) -> update(['status' => 0]);
			if($res)
			{
				return 0;
			}else
			{
				return 2;
			}
		}
	}

	//双击修改用户名
	public function ajaxName(Request $request)
	{
		$id = $request -> id;
		$name = $request -> user_name;

		$data = DB::table('users') -> where('user_name', $name) -> first();
		
		if($data)
		{
			return 4;
		}else
		{
			$res = DB::table('users') -> where('id', $id) -> update(['user_name' => $name]);
			if($res)
			{
				return 1;
			}else
			{
				return 0;
			}
		}
	}

	//edit
	public function edit($id)
	{
		$data = DB::table('users') -> where('id', $id) -> first();
		
		return view('admin.user.edit', ['data' => $data, 'title' => '用户编辑']);
	}

	//update
	public function update(Request $request)
	{
		$data = $request -> except('_token', 'id');

		// dd($data);
		
		//获取原来的图片
		$oldphoto = DB::table('users') -> where('id', $request -> id) -> first() -> photo;
		
		if($request -> hasFile('photo'))
		{
			if($request -> file('photo') -> isValid())
			{
				$suffix = $request -> file('photo') -> getClientOriginalExtension();
				$fileName = time() . mt_rand(10000,99999) . '.' . $suffix;
				//移动文件
				$move = $request -> file('photo') -> move('./uploads/yhtx', $fileName);
				
				if($move)
				{
					$data['photo'] = $fileName;
					//删除原来的图片
					unlink('./uploads/yhtx/' . $oldphoto);
				}
			}
		}

		//执行修改
		$res = DB::table('users') -> where('id', $request -> id) -> update($data);
	
		if($res)
		{
			return redirect('/admin/user/index') -> with(['info' => '修改成功']);
		}else
		{
			return back() -> with(['info' => '修改失败']);
		}
	}

	//删除
	public function delete($id)
	{
		//获取原来的图片
		$oldphoto = DB::table('users') -> where('id', $id) -> first() -> photo;
		
		$res = DB::table('users') -> delete($id);

		if($res)
		{
			//删除图片
			if(file_exists('./uploads/yhtx/' . $oldphoto))
			{
				unlink('./uploads/yhtx/' . $oldphoto);
			}

			return redirect('/admin/user/index') -> with(['info' => '删除成功']);
		}else
		{
			return back() -> with(['info' => '删除失败']);
		}
	}
}
